package com.example.computer_exam_training_sys.controller;

import com.example.computer_exam_training_sys.entity.Question;
import com.example.computer_exam_training_sys.entity.SysLog;
import com.example.computer_exam_training_sys.entity.User_Info;
import com.example.computer_exam_training_sys.service.SysLogService;
import com.example.computer_exam_training_sys.service.User_Info_Service;
import com.example.computer_exam_training_sys.ultils.AvatarUploadUtil;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@CrossOrigin
@RestController
@RequestMapping("/user")
public class User_Info_Controller {

    @Autowired
    private User_Info_Service userInfoService;
    @Autowired
    private SysLogService sysLogService;
    @Autowired
    private AvatarUploadUtil avatarUploadUtil;

    // 查询所有用户
    @GetMapping("/user_findall")
    public List<User_Info> getAllUsers() {
        return userInfoService.selectAll();
    }

    // 根据ID查询用户
    @GetMapping("/user_find/{id}")
    public User_Info getUserById(@PathVariable("id") int id) {
        return userInfoService.User_InfoselectByID(id);
    }

    // 新增用户
    @PostMapping("/user_add")
    public int addUser(@RequestBody User_Info user) {
        return userInfoService.insertUser(user);
    }

    // 更新用户
    @PostMapping("/user_update")
    public int updateUser(@RequestBody User_Info user) {
        return userInfoService.updateUser(user);
    }

    // 删除用户
    @DeleteMapping("/userdelete/{id}")
    public int deleteUser(@PathVariable("id") int id) {
        return userInfoService.deleteUser(id);
    }

    // 查询当日新增用户
    @GetMapping("/newuserstoday")
    public List<User_Info> getNewUsersToday() {
        return userInfoService.getNewUsersToday();
    }


    // 更新最近登录时间
    @PostMapping("/update_last_login/{id}")
    public int updateLastLogin(@PathVariable("id") int id) {
        return userInfoService.updateLastLogin(id);
    }

    // 登录接口
    @PostMapping("/login")
    public ResponseEntity<?> login(@RequestBody User_Info loginRequest,
                                   HttpServletRequest request) {

        User_Info user = userInfoService.findByUsername(loginRequest.getUsername());
        if (user == null) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("用户不存在");
        }

        if (!user.getPassword().equals(loginRequest.getPassword())) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("密码错误");
        }

        // 获取客户端信息
        String userAgent = request.getHeader("User-Agent");
        String clientIP = request.getRemoteAddr();

        // 更新最近登录时间
        userInfoService.updateLastLogin(user.getUserId());

        // 记录登录日志
        SysLog log = new SysLog();
        log.setUserID(user.getUserId());
        log.setLogContent("用户登录系统");
        log.setIpAddress(clientIP);
        log.setOs(getOS(userAgent != null ? userAgent : ""));
        log.setIe(getBrowser(userAgent != null ? userAgent : ""));
        sysLogService.insertLog(log);

        // 返回角色
        Map<String, Object> result = new HashMap<>();
        result.put("userId", user.getUserId());
        result.put("role", user.getIsAdmin() == 1 ? "admin" : "user");
        return ResponseEntity.ok(result);
    }

    // 新增：登录并返回用户详细信息
    @PostMapping("/login_info")
    public ResponseEntity<?> loginAndGetInfo(@RequestBody User_Info loginRequest) {
        User_Info user = userInfoService.findByUsername(loginRequest.getUsername());
        if (user == null) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("用户不存在");
        }
        if (!user.getPassword().equals(loginRequest.getPassword())) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("密码错误");
        }
        // 构建返回信息
        java.util.Map<String, Object> result = new java.util.HashMap<>();
        result.put("userid", user.getUserId());
        result.put("username", user.getUsername());
        result.put("avatar", user.getAvatar()); // avatar 字段
        if (user.getIsAdmin() != null && user.getIsAdmin() == 1) {
            result.put("adminid", user.getUserId());
        }
        return ResponseEntity.ok(result);
    }

    // 修改用户密码（推荐用JSON传参，避免参数缺失和类型问题）
    @PostMapping("/update_password")
    public ResponseEntity<?> updatePassword(@RequestBody Map<String, Object> param) {
        Integer userId = null;
        String oldPassword = null;
        String newPassword = null;
        try {
            Object userIdObj = param.get("userId");
            if (userIdObj == null) userIdObj = param.get("UserId"); // 兼容首字母大写
            if (userIdObj instanceof Integer) {
                userId = (Integer) userIdObj;
            } else if (userIdObj instanceof String) {
                userId = Integer.parseInt((String) userIdObj);
            }
            Object oldPwdObj = param.get("oldPassword");
            if (oldPwdObj == null) oldPwdObj = param.get("oldpassword");
            if (oldPwdObj != null) oldPassword = String.valueOf(oldPwdObj);
            Object newPwdObj = param.get("newPassword");
            if (newPwdObj == null) newPwdObj = param.get("newpassword");
            if (newPwdObj != null) newPassword = String.valueOf(newPwdObj);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("参数类型错误");
        }
        if (userId == null || oldPassword == null || newPassword == null) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("参数缺失");
        }
        boolean result = userInfoService.updatePassword(userId, oldPassword, newPassword);
        if (result) {
            return ResponseEntity.ok("密码修改成功");
        } else {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("原密码错误或用户不存在");
        }
    }

    // 头像上传接口
    @PostMapping("/upload_avatar")
    public ResponseEntity<?> uploadAvatar(@RequestParam("file") MultipartFile file, @RequestParam("userId") Integer userId) {
        try {
            if (file.isEmpty()) {
                return ResponseEntity.badRequest().body("请选择要上传的文件");
            }
            // 保存头像文件到前端public/avatars目录，返回文件名
            String fileName = avatarUploadUtil.saveAvatar(file, "public/avatars");
            // 只返回文件名，数据库更新交由前端调用 /set_avatar 完成
            return ResponseEntity.ok(fileName);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("头像上传失败：" + e.getMessage());
        }
    }


    // 更新用户头像接口
    @PostMapping("/update_avatar")
    public ResponseEntity<?> updateAvatar(@RequestBody Map<String, Object> param) {
        Integer userId = null;
        String avatar = null;
        try {
            Object userIdObj = param.get("userId");
            if (userIdObj == null) userIdObj = param.get("UserId");
            if (userIdObj instanceof Integer) {
                userId = (Integer) userIdObj;
            } else if (userIdObj instanceof String) {
                userId = Integer.parseInt((String) userIdObj);
            }
            Object avatarObj = param.get("avatar");
            if (avatarObj != null) avatar = String.valueOf(avatarObj);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("参数类型错误");
        }
        if (userId == null || avatar == null) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("参数缺失");
        }
        int result = userInfoService.updateAvatar(userId, avatar);
        if (result > 0) {
            return ResponseEntity.ok("头像更新成功");
        } else {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("头像更新失败");
        }
    }

    // 根据用户id更改头像路径
    @PostMapping("/set_avatar")
    public ResponseEntity<?> setAvatar(@RequestBody Map<String, Object> param) {
        Integer userId = null;
        String avatar = null;
        try {
            Object userIdObj = param.get("userId");
            if (userIdObj == null) userIdObj = param.get("UserId");
            if (userIdObj instanceof Integer) {
                userId = (Integer) userIdObj;
            } else if (userIdObj instanceof String) {
                userId = Integer.parseInt((String) userIdObj);
            }
            Object avatarObj = param.get("avatar");
            if (avatarObj != null) avatar = String.valueOf(avatarObj);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("参数类型错误");
        }
        if (userId == null || avatar == null) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("参数缺失");
        }
        int result = userInfoService.updateAvatar(userId, avatar);
        if (result > 0) {
            return ResponseEntity.ok("头像路径更新成功");
        } else {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("头像路径更新失败");
        }
    }

    // ✅ 新增：用于解析用户代理获取操作系统的方法
    private String getOS(String userAgent) {
        // 在这里添加操作系统判断逻辑
        if (userAgent.contains("Windows")) {
            return "Windows";
        } else if (userAgent.contains("Linux")) {
            return "Linux";
        } else if (userAgent.contains("Mac OS")) {
            return "macOS";
        }
        return "未知操作系统";
    }

    // ✅ 新增：用于解析用户代理获取浏览器的方法
    private String getBrowser(String userAgent) {
        // 在这里添加浏览器判断逻辑
        if (userAgent.contains("Chrome")) {
            return "Chrome";
        } else if (userAgent.contains("Firefox")) {
            return "Firefox";
        } else if (userAgent.contains("Safari")) {
            return "Safari";
        } else if (userAgent.contains("Edge")) {
            return "Edge";
        }
        return "未知浏览器";
    }

    @GetMapping("/user_findall_count")
    public int getTotalUserCount() {
        return userInfoService.getTotalUserCount();
    }
    //http://localhost:8080/user/allpage
    @GetMapping("/allpage")
    public PageInfo<User_Info> getAllpage(int page, int size) {
        PageInfo<User_Info> pageInfo = userInfoService.findAllpage(page, size);
        return pageInfo;

    }//测试成功
}
